<template>
  <div class="contractCheck-main">
    <div style="flex: 1; display: flex; flex-direction: column; padding: 0 20px; position: relative">
      <div class="contractCheck-main_left__content">
        <div class="contractCheck-main_left__content___top" v-if="!showFileUrls">
          <el-upload
            class="upload-demo contractCheck-main_upload"
            drag
            :action="uploadImgUrl"
            :headers="headers"
            :file-list="fileUrls"
            multiple
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :on-remove="handleAvatarRemove"
            :show-file-list="false"
            ref="uploadRef"
          >
            <el-image style="width: 60px; height: 60px" :src="upload" class="scalable-image" fit="cover" />
            <div>
              <div style="font-size: 18px; color: rgba(6, 10, 38, 0.8); font-weight: 600; line-height: 1.1">将文件拖到此处，或点击上传</div>
              <div
                style="
                  font-family: PingFangSC-Regular;
                  font-size: 12px;
                  color: rgba(6, 10, 38, 0.4);
                  font-weight: 400;
                  line-height: 1.1;
                  margin-top: 4px;
                "
              >
                只能上传jpg/png/jpeg/doc/docx/pdf文件
              </div>
            </div>
          </el-upload>
          <el-upload
            v-model:file-list="fileUrls"
            class="upload-demo"
            :action="uploadImgUrl"
            :headers="headers"
            multiple
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :on-remove="handleAvatarRemove"
            :show-file-list="false"
            ref="uploadRef"
          >
            <el-button type="primary" :icon="Paperclip">上传文件</el-button>
          </el-upload>
        </div>
        <div class="contractCheck-main_left__content___top1" v-else>
          <div class="file-list-container">
            <div v-for="(item, index) in fileUrls" :key="index" class="file-item">
              <div class="file-item_each">
                <el-image style="width: 30px; height: 30px" :src="getFileIcon(item.name, item)" class="scalable-image" fit="cover"></el-image>
                <div class="file-item_each__text">{{ item.name }}</div>
                <close-one
                  style="float: right; cursor: pointer"
                  theme="outline"
                  size="22"
                  fill="#000000"
                  :strokeWidth="1"
                  @click="removeFile(index)"
                />
              </div>
            </div>
            <div class="file-item">
              <div class="file-item_each each-other">
                <el-upload
                  v-model:file-list="fileUrls"
                  class="upload-demo"
                  :action="uploadImgUrl"
                  :headers="headers"
                  multiple
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  :on-remove="handleAvatarRemove"
                  :show-file-list="false"
                  ref="uploadRef"
                >
                  <folder-upload theme="outline" size="20" fill="#000000" :strokeWidth="1" />
                  <div
                    style="
                      font-size: 12px;
                      font-family: PingFangSC-Regular;
                      margin-left: 4px;
                      color: rgba(6, 10, 38, 0.5);
                      letter-spacing: 0;
                      line-height: 16px;
                      font-weight: 400;
                    "
                  >
                    继续上传文件
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
        <div style="margin-top: 10px">
          <div style="align-items: center; display: flex; justify-content: space-between">
            <el-radio-group v-model="chatType" @change="forceUpdate">
              <el-radio v-for="item in chatConfigList" :key="item.aiChatId" :label="item.chatType">{{ item.chatType }}</el-radio>
            </el-radio-group>
            <!-- <el-button style="float: right" size="small" type="danger" :icon="Delete" circle plain @click="clearFiles" /> -->
            <el-button style="float: right" size="small" @click="clearFiles" type="danger" :icon="Delete" plain>清空</el-button>
          </div>
          <el-input style="border-color: rgba(13, 83, 255, 0.07)" v-model="content" placeholder="请输入需求">
            <template #append>
              <span style="cursor: pointer; color: #fff" @click="submitCotent">分析</span>
              <!-- <search style="cursor: pointer" theme="outline" size="24" fill="#000000" :strokeWidth="1" @click="submitCotent" /> -->
            </template>
          </el-input>
        </div>
      </div>

      <div style="box-shadow: 0 0px 10px #666">
        <el-input
          class="contractCheck-main_input"
          type="textarea"
          :autosize="{ minRows: 20, maxRows: 20 }"
          placeholder="展示结果"
          v-model="resContent"
          readonly
        >
        </el-input>
      </div>
    </div>
    <!-- 样式一 -->
    <!-- <div style="flex: 1; display: flex; flex-direction: column; padding: 0 20px">
      <el-radio-group v-model="chatType" @change="forceUpdate">
        <el-radio v-for="item in chatConfigList" :key="item.aiChatId" :label="item.chatType">{{ item.chatType }}</el-radio>
      </el-radio-group>
      <el-input ref="inputField" placeholder="请输入内容" v-model="content" style="width: 360px" class="contractCheck-main_input">
        <template v-slot:prepend>需求</template>
      </el-input>
      <div style="text-align: center; margin-top: 15px">
        <el-button @click="clearFiles" type="danger" :icon="Delete" plain>清空</el-button
        ><el-button @click="submitCotent" type="primary" plain>提交分析</el-button>
      </div>
      <el-upload
        class="upload-demo contractCheck-main_upload"
        drag
        :action="uploadImgUrl"
        :headers="headers"
        show-file-list
        :file-list="fileUrls"
        multiple
        :before-upload="beforeAvatarUpload"
        :on-success="handleAvatarSuccess"
        :on-error="handleAvatarError"
        :on-remove="handleAvatarRemove"
        ref="uploadRef"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传jpg/png/jpeg/doc/docx/pdf文件</div>
        </template>
      </el-upload>
    </div> -->
    <div style="flex: 1; margin-left: 0px">
      <el-button style="float: right" type="primary" icon="Document" @click="logout" class="export-btn"> 退出登录 </el-button>

      <div class="sound-right">
        <div class="mainBox mainBox-right">
          <div style="margin-bottom: 10px; font-weight: 600; color: #515a6e">任务列表</div>
          <el-table v-loading="loading" :data="aiTaskList" @selection-change="handleSelectionChange">
            <el-table-column type="index" label="编号" width="55" align="center" />
            <el-table-column label="文件类型" align="center" prop="taskType" />
            <el-table-column label="任务状态" align="center" prop="taskStatus">
              <template #default="scope">
                <dict-tag :options="ai_task_status" :value="scope.row.taskStatus" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" @click="vieRes(scope.row.taskContent)" :disabled="scope.row.taskStatus == 0 ? true : false"
                  >查看结果</el-button
                >
                <el-button link type="primary" @click="viewImage(scope.row.taskId)" :disabled="scope.row.taskStatus == 0 ? true : false"
                  >图片分析</el-button
                >
                <!-- <el-button link type="danger" @click="deteleAI(scope.row.taskId)">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>

    <el-dialog v-model="openMindMax" title="图片预览" width="80%">
      <div class="reviewImageBox">
        <div class="imageBox" v-for="(item, index) in srcList" :key="index" @click="preViewImage(index)"><img :src="item" alt="" /></div>
      </div>
      <el-image-viewer
        v-if="showPreview"
        :infinite="false"
        :url-list="srcList"
        show-progress
        :initial-index="showIndex"
        @close="showPreview = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listChatConfig, sendMessageContentPic, getAiAskList, detAiAskList, getContractTaskImage } from '@/api/aiManage/contractAi/index';
import { initWebSocket } from '@/utils/websocket';
import useNoticeStore from '@/store/modules/notice';
import type { UploadInstance } from 'element-plus';
import { globalHeaders } from '@/utils/request';
import useUserStore from '@/store/modules/user';
import { Microphone, Mute, VideoPause, VideoPlay, Headset, Upload, Download, Delete, Paperclip } from '@element-plus/icons-vue';
import upload from '@/assets/images/file_upload.png';
import filePdf from '@/assets/images/pdf.png';
import fileWord from '@/assets/images/word.png';
import filePic from '@/assets/images/file_pic.png';
import { FolderUpload, CloseOne, Search } from '@icon-park/vue-next';
import '@icon-park/vue-next/styles/index.css'; // 导入图标样式
import { deteleUAV } from '@/api/aiManage/UAVinspection';

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const noticeStore = storeToRefs(useNoticeStore());
const chatConfigList = ref([]);
const chatType = ref('');
const content = ref('分析劳动合同中是否存在不合理的条款');
const resContent = ref('');
const fileUrls = ref([]);
const headers = ref(globalHeaders());
const uploadImgUrl = baseUrl + '/resource/oss/upload/compress'; // 上传的图片服务器地址
const uploadRef = ref<UploadInstance>();
const userId = ref(userStore.userId);
const showFileUrls = ref(false);

const timer = ref(null);
const srcList = ref([]);
const showPreview = ref(false);
const openMindMax = ref(false);
const showIndex = ref(0);

// 路由
const router = useRouter();

// 任务列表
const loading = ref(false);
const { ai_task_status, ai_task_type } = toRefs<any>(proxy?.useDict('ai_task_status', 'ai_task_type'));
const ids = ref([]);
const single = ref(false);
const multiple = ref(true);
const selection = ref([]);
const aiTaskList = ref([]);
const total = ref(0);
const initFormData = {
  taskId: undefined,
  userId: undefined,
  taskType: undefined,
  taskName: undefined,
  taskContent: undefined,
  taskStatus: undefined
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    userId: userId.value.toString(),
    taskType: undefined,
    taskName: undefined,
    taskContent: undefined,
    taskStatus: undefined,
    params: {}
  },
  rules: {
    taskId: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 查看结果 */
const vieRes = (val) => {
  resContent.value = val;
};

/** 查询ai任务列表 */
const getList = async () => {
  loading.value = true;
  clearInterval(timer.value);
  const res = await getAiAskList(queryParams.value);
  aiTaskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  res.rows.forEach((item) => {
    clearInterval(timer.value);
    if (item.taskStatus == 0) {
      timer.value = setInterval(() => {
        getList();
      }, 3000);
    }
  });
};

const getChatConfigList = async () => {
  const res = await listChatConfig();
  if (res.code === 200) {
    chatConfigList.value = res.rows;
    chatType.value = res.rows[0].chatType;
  }
};

const forceUpdate = (val) => {
  const contentItem = chatConfigList.value.find((item) => item.chatType === val);
  content.value = contentItem ? contentItem.demand : null;
};

const beforeAvatarUpload = (file: any) => {
  let index = file.name.lastIndexOf('.');
  let str = file.name.substr(index + 1);
  const isFile = ['doc', 'docx', 'pdf', 'jpg', 'png', 'jpeg'].indexOf(str.toLowerCase()) !== -1;
  if (!isFile) {
    showFileUrls.value = false;
    proxy.$modal.msgError('上传图片只能是 JPG/PNG/JPEG/DOC/DOCX/PDF  格式!');
    return false;
  }
  proxy?.$modal.loading('正在上传文件，请稍候...');
  return true;
};

const handleAvatarSuccess = (res: any, file: any, fileList: any) => {
  if (res.code == 200) {
    fileUrls.value = fileList;
    proxy?.$modal.closeLoading();
    showFileUrls.value = true;
  } else {
    proxy?.$modal.msgError(res.msg);
    proxy?.$modal.closeLoading();
    showFileUrls.value = false;
  }
};

const handleAvatarError = (err: any) => {
  proxy?.$modal.msgError(err.msg);
  proxy?.$modal.closeLoading();
  showFileUrls.value = false;
};

const handleAvatarRemove = (file: any, fileList: any) => {
  fileUrls.value = fileList;
};

const removeFile = (index: number) => {
  fileUrls.value.splice(index, 1);
  if (fileUrls.value.length == 0) {
    showFileUrls.value = false;
  }
};

const clearFiles = () => {
  uploadRef.value!.clearFiles();
  fileUrls.value = [];
  resContent.value = '';
  showFileUrls.value = false;
};

const submitCotent = async () => {
  // conectWebSocket();
  if (fileUrls.value.length == 0) {
    ElMessage.error('您还未上传文件！');
    return;
  }
  proxy?.$modal.loading('正在分析中，请稍候...');
  resContent.value = '';
  const newArr = fileUrls.value
    .map((item) => {
      // 检查 item 中是否存在 response 对象，以及 response 对象中是否存在 data 对象，data 对象中是否存在 url 属性
      if (item.response && item.response.data && item.response.data.url) {
        return item.response.data.url;
      }
      return null; // 如果不满足条件，返回 null
    })
    .filter((item) => item !== null); // 过滤掉 null 值
  let data = {
    chatType: '',
    content: '',
    fileUrls: [],
    sessionKey: userId.value,
    topic: 'contentWebSocket'
  };
  data.chatType = chatType.value;
  data.content = content.value;
  data.fileUrls = newArr;
  await sendMessageContentPic(data);
  setTimeout(() => {
    getList();
    proxy.$modal.closeLoading();
  }, 3000);
};

const conectWebSocket = () => {
  let protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  initWebSocket(protocol + window.location.host + import.meta.env.VITE_APP_BASE_API + '/resource/websocket', (message) => {
    if (message && JSON.parse(message).topic === 'contentWebSocket') {
      proxy.$modal.closeLoading();
      try {
        // 尝试解析JSON
        const parsedMessage = JSON.parse(message);
        resContent.value += parsedMessage.content;
      } catch (error) {
        // 处理解析错误
        console.error('解析JSON时出错:', error);
        console.log('原始消息:', message);
      }
    }
  });
  // initWebSocket(protocol + '192.168.110.113:8003/resource/websocket', (message) => {
  //   if (message && JSON.parse(message).topic === 'contentWebSocket') {
  //     proxy.$modal.closeLoading();
  //     try {
  //       // 尝试解析JSON
  //       const parsedMessage = JSON.parse(message);
  //       resContent.value += parsedMessage.content;
  //     } catch (error) {
  //       // 处理解析错误
  //       console.error('解析JSON时出错:', error);
  //       console.log('原始消息:', message);
  //     }
  //   }
  // });
};

const getFileIcon = (name: string, item: any) => {
  const ext = name.split('.').pop()?.toLowerCase();
  if (ext === 'pdf') {
    return filePdf;
  } else if (ext === 'docx' || ext === 'doc') {
    return fileWord;
  } else if (['jpg', 'jpeg', 'png'].includes(ext)) {
    return item.response?.data.url;
  }
  return filePic; // 默认图标
};

const logout = async () => {
  await ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  let loginType = userStore.loginType ? JSON.parse(JSON.stringify(userStore.loginType)) : '';
  userStore.logout().then(() => {
    if (loginType) {
      router.replace({
        path: '/creativeProjectsLogin',
        query: {
          redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
        }
      });
    } else {
      router.replace({
        path: '/login',
        query: {
          redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
        }
      });
    }
    loginType = '';
  });
};

const viewImage = async (taskId) => {
  const res = await getContractTaskImage(taskId);
  if (res.code === 200) {
    srcList.value = [];
    res.rows.forEach((item) => {
      srcList.value.push(item.imagePath);
    });
    openMindMax.value = true;
  }
};

const preViewImage = (index) => {
  showPreview.value = true;
  showIndex.value = index;
};

const deteleAI = async (taskId) => {
  ElMessageBox.confirm('确定删除该任务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await detAiAskList(taskId);
      if (res.code == 200) {
        getList();
        ElMessage({
          type: 'success',
          message: '删除成功！'
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      });
    });
};
onMounted(() => {
  getChatConfigList();
  getList();
});
</script>

<style lang="scss" scoped>
.reviewImageBox {
  padding: 20px 0;
  display: flex;
  justify-content: center;
  flex-wrap: wrap; // 添加换行属性
  gap: 10px; // 添加间距
}
.reviewImageBox .imageBox {
  width: calc(33.333% - 7px); // 计算宽度留出间隙空间
  overflow: hidden;
  border-radius: 10px;
  // margin-right: 10px;
  margin-right: 0;
}
// .reviewImageBox .imageBox:nth-child(3n + 1) {
//   border-radius: 20px 10px 10px 20px;
// }

// .reviewImageBox .imageBox:nth-child(3n) {
//   border-radius: 10px 20px 20px 10px;
// }

.reviewImageBox .imageBox img {
  width: 100%;
  height: auto;
  cursor: pointer;
}
.contractCheck-main {
  padding: 20px;
  display: flex;
  flex-direction: row;
  min-height: calc(100vh - 84px);
  background-color: #f0f4f9; //浅紫
}
/* ::v-deep .contractCheck-main_upload .el-upload-list {
  height: 150px;
  overflow: auto;
} */
.contractCheck-main_input,
.contractCheck-main_bth {
  margin-top: 15px;
}
::v-deep .contractCheck-main_input .el-textarea__inner {
  border-radius: 15px;
  border: 1px solid #ffffff;
  box-shadow: unset;
}

/* 左边内容 */
.contractCheck-main_left__content {
  width: 100%;
  height: 40%;
  border-radius: 15px;
  background-color: #fff;
  padding: 5px 11px;
  margin: 0 auto;
  margin-bottom: 30px;
  box-sizing: border-box;
  box-shadow: 0 0px 10px #666;
  // position: absolute;
  // top: 30%;
  // left: 50%;
  // transform: translate(-50%, -30%);
}

.contractCheck-main_left__content___top {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 6px;
  background-image: linear-gradient(-90deg, rgba(17, 155, 255, 0.03) 0%, rgba(217, 255, 231, 0.05) 49%, rgba(105, 82, 255, 0.03) 100%);
  border-radius: 12px;
  width: 100%;
  position: relative;
  height: 170px;
  // cursor: pointer;
}

.contractCheck-main_left__content___top {
  display: flex;
  flex-direction: column;
  gap: 6px;
  background-image: linear-gradient(-90deg, rgba(17, 155, 255, 0.03) 0%, rgba(217, 255, 231, 0.05) 49%, rgba(105, 82, 255, 0.03) 100%);
  border-radius: 12px;
  width: 100%;
  position: relative;
  height: 170px;
  // cursor: pointer;
}

.file-list-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  height: 170px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.file-item_each {
  position: relative;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 12px 0 10px;
  width: 100%;
  height: 72px;
  background-color: #fff;
  border-radius: 12px;
  border: 1px solid rgba(13, 83, 255, 0.07);
}

.each-other {
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.file-item_each__text {
  font-family: PingFangSC-Regular;
  font-size: 14px;
  color: rgba(6, 10, 38, 0.8);
  margin-left: 4px;
}

.contractCheck-main_upload {
  width: 100%;
}

::v-deep .contractCheck-main_upload .el-upload-dragger {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  border: unset;
  background-color: unset;
}

/* 右边文本内容 */
.contractCheck-main_right__scroll {
  height: 100%;
  width: 100%;
  overflow-y: scroll;
  border-radius: 15px;
  background-color: #fff;
}

::v-deep .contractCheck-main_left__content .el-input-group__append {
  background-color: #409eff;
}
</style>
